import { useCallback, useEffect } from "react"
import { ActivityIndicator, BackHandler, View, ViewStyle } from "react-native"
import { router, useFocusEffect, useLocalSearchParams } from "expo-router"
import { useNavigation } from "@react-navigation/native"

import { Loading, Text } from "@/components"
import { useStores } from "@/models"

const AppLoadingPage = () => {
  const navigation = useNavigation()
  const { systemStore } = useStores()
  const params: any = useLocalSearchParams()
  useFocusEffect(
    useCallback(() => {
      const timeout = setTimeout(() => {
        router.back()
      }, params.maxDuration || 15000)

      const noBack = () => true
      const handler = BackHandler.addEventListener("hardwareBackPress", noBack)

      return () => {
        clearTimeout(timeout)
        handler.remove()
      }
    }, []),
  )

  useEffect(() => {
    console.log(
      "systemStore.showLoadingModal changed:",
      systemStore.showLoadingModal,
      "current route:",
      navigation,
    )
    if (!systemStore.showLoadingModal) {
      router.back()
    }
  }, [systemStore.showLoadingModal])

  return (
    <View style={$container}>
      {/*<ActivityIndicator size={48} />*/}
      <Loading isLoading={true} size={"sm"} />
      {/*{params.message ? <Text>{params.message}</Text> : <></>}*/}
    </View>
  )
}

export default AppLoadingPage

const $container: ViewStyle = {
  flex: 1,
  backgroundColor: "rgba(0,0,0,0.3)",
  justifyContent: "center",
  alignItems: "center",
}
